package com.fak.wid;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;  



import android.content.ContentValues;  
import android.content.Context;  
import android.database.Cursor;  
import android.database.SQLException;  
import android.database.sqlite.SQLiteDatabase;  
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;  
import android.util.Log;  


public class DBAdapter {
	
	
	int id = 0;  
    public static final String KEY_ROWID = "_id";  
    public static final String KEY_QUOTE = "Quote";
    public static final String KEY_QUOTE_FAVORIT = "FavoritQuote";
    private static final String TAG = "DBAdapter";  
    private static String DB_PATH = "/data/data/com.fak.wid/databases/"; //ïóòü ê áàçå äàííûõ /data/data/<èìÿ âàøåãî ïàêåòà>/databases/
    private static String DB_NAME = "QuoteDataBase"; //èìÿ ôàéëà áàçû äàííûõ
    private static final String DATABASE_TABLE = "tblRandomQuotes";
    private static final String DATABASE_TABLE_FAVORIT = "tblFavoritQuotes"; 

  
   

   
  
  
    public static class DatabaseHelper extends SQLiteOpenHelper  
    {  
     
    	private final Context myContext;
        
        public DatabaseHelper(Context context) {
        	 
        	super(context, DB_NAME, null, 1);
            this.myContext = context;
        }	

        public void createDataBase() throws IOException{
            boolean dbExist = checkDataBase();
     
            if(!dbExist){ //åñëè íàøà áàçà íå ñóùåñòâóåò  ñêîïèðîâàòü åž ñ ðåñóðñîâ ïðèëîæåíèÿ
                getReadableDatabase();
     
                try {
                    copyDataBase();
                } catch (IOException e) {}
            }
     
        }
     
   
        private boolean checkDataBase(){
     
        	SQLiteDatabase checkDB = null;
     
        	try{
        		String myPath = DB_PATH + DB_NAME;
        		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
     
        	}catch(SQLiteException e){
            }
     
        	if(checkDB != null){
     
        		checkDB.close();
     
        	}
     
        	return checkDB != null ? true : false;
        }
     
       
        private void copyDataBase() throws IOException{
            InputStream myInput = myContext.getAssets().open(DB_NAME);
            String outFileName = DB_PATH + DB_NAME;
            OutputStream myOutput = new FileOutputStream(outFileName);
            byte[] buffer = new byte[1024];
        	int length;
        	while ((length = myInput.read(buffer))>0){
        		myOutput.write(buffer, 0, length);
        	}
        	myOutput.flush();
        	myOutput.close();
        	myInput.close();
     
        }
       
        
        @Override  
        public void onCreate(SQLiteDatabase db)  
        {  
        
        }  
       
        @Override  
        public void onUpgrade(SQLiteDatabase db, int oldVersion,  
                              int newVersion)  
        {  
            
            db.execSQL("DROP TABLE IF EXISTS tblRandomQuotes"); 
            db.execSQL("DROP TABLE IF EXISTS tblFavoritQuotes");
            onCreate(db);  
        }  
    }  
    
private final Context context;  
private DatabaseHelper DBHelper;  
private SQLiteDatabase db;  
    
    public DBAdapter(Context ctx)  
    {  
        this.context = ctx;  
        DBHelper = new DatabaseHelper(context);  
      
       
    }  
      
    

    public  DBAdapter open() throws SQLException{
    
        String myPath = DB_PATH + DB_NAME;
    	db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    	
    	
    	   return this;  
    }
   
    

    public void close()  
    {  
        DBHelper.close();  
    }  
    
    public long insertQuote(String Quote)  
    {  
        ContentValues initialValues = new ContentValues();  
        initialValues.put(KEY_QUOTE, Quote);  
        return db.insert(DATABASE_TABLE, null, initialValues);  
    }  
    public long insertFavoritQuote(String FavoritQuote)  
    {  
        ContentValues initialValuesFavorit = new ContentValues();  
        initialValuesFavorit.put(KEY_QUOTE_FAVORIT, FavoritQuote);  
        return db.insert(DATABASE_TABLE_FAVORIT, null, initialValuesFavorit);  
    }  
    public int getAllEntries()  
    {  
        Cursor cursor = db.rawQuery(  
                    "SELECT COUNT(Quote) FROM tblRandomQuotes", null);  
                if(cursor.moveToFirst()) {  
                    return cursor.getInt(0);  
                }  
                return cursor.getInt(0);  
      
    }  
    
    
    public String getRandomEntry()  
    {  
   
        id = getAllEntries();  
        Random random = new Random();
        int rand = random.nextInt(getAllEntries());  
        if(rand == 0)  
            ++rand;  
        Cursor cursor = db.rawQuery(  
                    "SELECT Quote FROM tblRandomQuotes WHERE _id = " + rand, null);  
                if(cursor.moveToFirst()) {  
                    return cursor.getString(0);  
                }  
                return cursor.getString(0);  
   
    }  
   
    public Cursor getAllData() 
    {
      return db.query(DATABASE_TABLE_FAVORIT, new String[] {KEY_ROWID,KEY_QUOTE_FAVORIT},null,null,null,null,null);
    }
    
    public boolean deleteData(long rowId) 
    {
    	return db.delete(DATABASE_TABLE_FAVORIT, KEY_ROWID + 
        		"=" + rowId, null) > 0; 
        		
    }
    
}